<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Models\yb\CouponModel;
use App\Models\yb\GoodsModel;
use App\Models\yb\GoodsTypeModel;
use App\Models\yb\GoodsWarehouseModel;
use App\Models\yb\UserCouponModel;
use App\Models\yb\CouponPackageModel;
use App\Models\yb\UserModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;


class CouponController extends Controller
{

    /**
     * Get a JWT via given credentials.
     *  优惠券列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function CouponListing(Request $request)
    {
        $openid = $request->post('openid');
        if(empty($openid)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $user_data = UserModel::where(['openid'=>$openid])->first();

        $page = $request->post('page', 1);

        $take = $request->post('take', 10);

        $type = $request->post('type', 1);

        if($type == 1){

            $data = CouponModel::where(['status'=>1])->orderBy('created_at','desc')->skip(($page - 1) * $take)->take($take)->get();

            foreach($data as $key=>$val){
//
                $user_coupon_data = UserCouponModel::where(['user_id'=>$user_data['id'],'coupon_id'=>$val['id']])->select(['is_used','validity_start','validity_end'])->first();

                $data[$key]['validity_start'] = $user_coupon_data['validity_start'];

                $data[$key]['validity_end'] = $user_coupon_data['validity_end'];

                if(empty($user_coupon_data) && $val['distribution_type']!=1){
                    unset($data[$key]);
                    continue;
                }
                if(!empty($user_coupon_data)){
                    if($data[$key]['validity_end']<date('Y-m-d',time())){
                       $data[$key]['status'] = 4; //未使用
                    }else{
                        if($user_coupon_data['is_used'] == 0){
                            $data[$key]['status'] = 2; //未使用
                        }else{
                            $data[$key]['status'] = 3; //已使用
                        }
                    }

                }
            }
        }elseif($type == 2){
            $user_coupon_data = UserCouponModel::where(['user_id'=>$user_data['id']])->select(['coupon_id'])->get();

            if(!empty($user_coupon_data)){
                $user_coupon_data = $user_coupon_data->toArray();
                $user_coupon_id = array_column($user_coupon_data,'coupon_id');
                $data = CouponModel::where(['status'=>1])->where(['distribution_type'=>1])->whereNotIn('id',$user_coupon_id)->orderBy('created_at','desc')->skip(($page - 1) * $take)->take($take)->get();
            }else{
                $data = CouponModel::where(['status'=>1])->where(['distribution_type'=>1])->orderBy('created_at','desc')->skip(($page - 1) * $take)->take($take)->get();
            }

        }elseif($type == 3){
            $user_coupon_data = UserCouponModel::where(['user_id'=>$user_data['id']])->orderBy('created_at','desc')->skip(($page - 1) * $take)->take($take)->get();

            $data = array();
            foreach($user_coupon_data as $key=>$val) {

                $coupon_data = CouponModel::where(['id' => $val['coupon_id']])->first();
                $coupon_data['validity_start'] = $val['validity_start'];
                $coupon_data['validity_end'] = $val['validity_end'];
                if(!empty($coupon_data)){
                    $data[$key] = $coupon_data;
                    if ($val['is_used'] == 0) {
                        $data[$key]['status'] = 2; //未使用
                    } else {
                        $data[$key]['status'] = 3; //已使用
                    }
                    if($val['validity_end']<date('Y-m-d',time())){
                        $data[$key]['status'] = 4; //已过期
                    }
                }
            }
        }

        $list = array();

        foreach($data as $key=>$val){
            $list[] = $val;
        }

        foreach($list as $key=>$val){
            if($val['type'] == 1){
                $list[$key]['promotion_full_type_name'] = "全场通用";
            }elseif ($val['type'] == 2){
                $goods_type = GoodsTypeModel::where(['id'=>$val['goods_type']])->first();
                $list[$key]['promotion_full_type_name'] = "适用".$goods_type['title'];
            }elseif ($val['type'] == 3){
                $goods_data = GoodsWarehouseModel::where(['id'=>$val['goods_warehouse_id']])->first();
                $list[$key]['promotion_full_type_name'] = "适用".$goods_data['goods_title'];
            }
        }

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$list]);

    }

    /**
     * Get a JWT via given credentials.
     *  领取优惠券
     * @return \Illuminate\Http\JsonResponse
     */
    public function CouponReceive(Request $request)
    {
        $openid = $request->post('openid');
        if(empty($openid)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $user_data = UserModel::where(['openid'=>$openid])->first();

        $coupon_id = $request->post('coupon_id');

        $coupon_data = CouponModel::where(['id'=>$coupon_id,'status'=>1])->first();
        if(empty($coupon_data)){
            return response()->json(['code'=>'401','msg' => '该优惠券已下架']);
        }

        $user_coupon_data = UserCouponModel::where(['user_id'=>$user_data['id'],'coupon_id'=>$coupon_id])->first();
        if(!empty($user_coupon_data)){
            return response()->json(['code'=>'401','msg' => '您已领取过该优惠券']);
        }

        UserCouponModel::insert([
            'user_id' => $user_data['id'],
            'openid' => $openid,
            'goods_type' => $coupon_data['goods_type'],
            'coupon_id' => $coupon_id,
            'validity_start' => date('Y-m-d'),
            'validity_end' => date('Y-m-d',strtotime("+".$coupon_data['validity_after']." day")),
            'promotion_full' => $coupon_data['promotion_full'],
            'promotion_reduce' => $coupon_data['promotion_reduce'],
            'created_at' => date('Y-m-d H:i:s',time())
        ]);

        CouponModel::where(['id'=>$coupon_id])->increment('received_number');

        return response()->json(['code'=>'200','msg' => '领取成功']);

    }

    /**
     * Get a JWT via given credentials.
     *  我的优惠券列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function MyListing(Request $request)
    {
        $openid = $request->post('openid');

        $user_data = UserModel::where(['openid'=>$openid])->first();

        if(empty($user_data)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $page = $request->post('page', 1);

        $take = $request->post('take', 20);
        
        $aa = $request->post('aa');

        $goods_id =  $request->post('goods_id', 0);

        $goods_data = GoodsModel::where(['id'=>$goods_id,'status'=>1])->first();

        if(empty($goods_data)){
            return response()->json(['code'=>'203','msg' => '商品已下架']);
        }

        $user_coupon_data = UserCouponModel::where(['user_id'=>$user_data['id'],'is_used'=>0,'status'=>1])
            ->where('promotion_full','<=',$goods_data['goods_price']+0)
            ->orderBy('created_at','desc')
            ->skip(($page - 1) * $take)
            ->take($take)
            ->get();
            

        $coupon_list = array();

        foreach($user_coupon_data as $key=>$val){
            $coupon_data= CouponModel::where((['id'=>$val['coupon_id']]))->first();
            $coupon_data['validity_start'] = $val['validity_start'];
            $coupon_data['validity_end'] = $val['validity_end'];
            if($coupon_data['validity_end']<date('Y-m-d',time())){
                continue;
            }
            if($coupon_data['type'] == 2){
                if($coupon_data['goods_type'] != $goods_data['goods_type']){
                    continue;
                }
            }
            if($coupon_data['type'] == 3){
                if($coupon_data['goods_warehouse_id'] != $goods_data['goods_warehouse_id']){
                    continue;
                }
            }
            $coupon_list[] = $coupon_data;
        }
        return response()->json(['code'=>'200','msg' => '请求成功','user_coupon_data'=>$coupon_list]);

    }

    /**
     * Get a JWT via given credentials.
     * 新人大礼包
     * @return \Illuminate\Http\JsonResponse
     */
    public function PackageListing(Request $request)
    {
        $openid = $request->post('openid');

        $coupon_package_data = CouponPackageModel::first();
        
        if(!empty($coupon_package_data)){
                $coupon_data = CouponModel::whereIn('id',$coupon_package_data['coupon_id'])->get();

        if(!empty($openid)){

            $user_data = UserModel::where(['openid'=>$openid])->first();

            if($user_data['is_receive_package'] == 0){

                foreach ($coupon_data as $key=>$val){
                    $coupon_list[]=[
                        'user_id' => $user_data['id'],
                        'openid' => $openid,
                        'goods_type' => $val['goods_type'],
                        'coupon_id' => $val['id'],
                        'status' => $val['status'],
                        'validity_start' => date('Y-m-d'),
                        'validity_end' => date('Y-m-d',strtotime("+".$val['validity_after']." day")),
                        'promotion_full' => $val['promotion_full'],
                        'promotion_reduce' => $val['promotion_reduce'],
                        'type' => 2,
                        'created_at' => date('Y-m-d H:i:s',time())
                    ];
                }

                CouponModel::whereIn('id',$coupon_package_data['coupon_id'])->increment('received_number');

                UserCouponModel::insert($coupon_list);

                UserModel::where(['openid'=>$openid])->update(['is_receive_package'=>1]);

                $data['title'] = $coupon_package_data['title'];

                $data['coupon_data'] = $coupon_data;

                return response()->json(['code'=>'200','msg' => '请求成功','data'=>$data]);

            }
        }
        }

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>array()]);

    }

}
